/*
 * @Author: fubobo
 * @Date: 2025-07-29 15:21:00
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-07-29 16:47:59
 * @Description: 回到顶部，配合 scroll-view 和 wotui 组件使用。后续可兼容全局滚动
 */

export default class UseBackTop {
  public scrollTop = ref<number>(0); // scroll-view 容器滚动距离
  public recordScrollTop = ref<number>(0); // 记录滚动距离
  private duration = 250;
  private animationTimer: number | null = null;

  constructor(duration?: number) {
    this.duration = duration || this.duration;

    // 清理定时器
    onUnmounted(() => {
      if (this.animationTimer) clearInterval(this.animationTimer);
    });
  }

  scroll = (e: any) => {
    this.recordScrollTop.value = e.detail.scrollTop;
  };

  goTop = () => {
    this.scrollTop.value = this.recordScrollTop.value;

    nextTick(() => {
      // scroll-view 自带延迟动画
      this.scrollTop.value = 0;
    });

    // if (this.animationTimer) clearInterval(this.animationTimer);

    // const startTop = this.scrollTop.value;
    // const startTime = Date.now();
    // const duration = this.duration;

    // const scroll = () => {
    //   const currentTime = Date.now();
    //   const elapsed = currentTime - startTime;

    //   if (elapsed >= duration) {
    //     this.scrollTop.value = 0;
    //     if (this.animationTimer) {
    //       clearInterval(this.animationTimer);
    //       this.animationTimer = null;
    //     }
    //     return;
    //   }

    //   // 使用缓动函数
    //   const progress = elapsed / duration;
    //   const easeOut = 1 - Math.pow(1 - progress, 3); // 缓出效果
    //   this.scrollTop.value = startTop * (1 - easeOut);
    // };

    // // 使用setInterval代替requestAnimationFrame(兼容微信小程序，省的分平台)
    // this.animationTimer = setInterval(scroll, 16) as unknown as number;
  };
}
